import propTypes from 'prop-types';
import React, { Component } from 'react';
import {
  View,
  Text,
  StyleSheet,
  TouchableOpacity,
  TouchableWithoutFeedback,
  Image,
  Dimensions,
} from 'react-native';
import {Actions} from 'react-native-router-flux';
import CommonStyles from './styles';
import Icon from 'react-native-vector-icons/MaterialCommunityIcons';
import api from './api';
import {AlbumView, Overlay, PullPicker} from 'teaset';
import Toast from 'react-native-easy-toast';
import {Avatar, Divider} from 'react-native-elements';
import Button from 'antd-mobile/lib/button';
import Config from './config';
import util from './util';

const {width, height} = Dimensions.get('window');

class CommentItem extends Component {
  static propTypes = {
    item: propTypes.shape({}).isRequired,
  }

  images = {}
  thumbs = {}
  imageElems = {}

  gotoCommentDetail(item) {
    console.log("gotoCommentDetail");
    Actions.CommentDetail({"router_params": {"comment": item}, "title": item.floor_num_human});
  }

  fixImageHeight(nowWidth, url, key) {
    Image.getSize(url, (acturalWidth, acturalHeight) => {
      console.log(url, acturalWidth, acturalHeight);
      let nowHeight = (nowWidth * acturalHeight) / acturalWidth;
      this.imageElems[key].setNativeProps({
        style: {height: nowHeight}
      })
    })
  }

  viewImage(cid, image) {
    let index = 0;
    let images = Object.keys(this.images[cid]).map((_key, _index) => {
      if (_key == image) {
        index = _index;
      }
      return this.images[cid][_key];
    });
    let thumbs = Object.keys(this.thumbs[cid]).map((_key, _index) => {
      return this.thumbs[cid][_key];
    });
    let touchableView = this.imageElems[image];
    touchableView.measure((x, y, width, height, pageX, pageY) => {
      let overlayView = (
        <Overlay.PopView
          style={{}}
          containerStyle={{flex: 1}}
          overlayOpacity={1}
          type='custom'
          customBounds={{x: pageX, y: pageY, width, height}}
          ref={v => this.fullImageView = v}
        >
          <AlbumView
            style={{flex: 1}}
            control={true}
            images={images}
            thumbs={thumbs}
            defaultIndex={index}
            onPress={() => this.fullImageView && this.fullImageView.close()}
            />
        </Overlay.PopView>
      );
      Overlay.show(overlayView);
    })
  }

  render() {
    let item = this.props.item;
    return (
      <View key={item.key} style={[CommonStyles.container, styles.itemWrap]}>
        <View style={[CommonStyles.row, styles.topicHeader]}>
          <Avatar small rounded source={{uri: item.user.data.avatar}} />
          <View>
            <Text style={[styles.nickname]}>{item.user.data.name}</Text>
            <View style={[CommonStyles.row]}>
              <Text style={[styles.updateTime]}>{item.created_at_human}</Text>
              <View style={[CommonStyles.row, styles.countWrap]}>
                <Text style={styles.viewCount}>{item.floor_num_human}</Text>
              </View>
            </View>
          </View>
        </View>
        <TouchableWithoutFeedback onPress={() => this.gotoCommentDetail(item)}>
        <View style={item.floor_num > 1 ? styles.itemContentWrap : {}}>
        {item.detail.data.content.map((_content, i) => {
          if (_content.type == "text") {
            return (
              <View style={[styles.contentWrap]} key={item.key + i}>
                <Text>{_content.data.text}</Text>
              </View>
            )
          } else if (_content.type == "image") {
            let nowWidth = width - (item.floor_num == 1 ? 30 : 64);
            let cid = item.detail.data.cid;
            let key = _content.data.key;
            let image = util.getThumbImageUrl(key);
            let thumb = util.getThumbImageUrl(key, 350);
            if (!this.images[cid]) {
              this.images[cid] = {};
            }
            if (!this.thumbs[cid]) {
              this.thumbs[cid] = {};
            }
            if (!this.images[cid][image]) {
              this.images[cid][image] = {uri: image};
              this.thumbs[cid][image] = {uri: thumb};
            }
            return (
              <TouchableOpacity 
                key={item.key + i}
                activeOpacity={0.8}
                onPress={() => this.viewImage(cid, image)}
                ref={(ref) => {
                  this.imageElems[image] = ref;
                }}
              >
                <Image
                  ref={ref => this.imageElems[key] = ref}
                  source={{uri: thumb}} 
                  onLoadStart={() => this.fixImageHeight(nowWidth, thumb, key)}
                  style={[styles.detailAttachmentImage, {width: nowWidth}]} 
                />
              </TouchableOpacity>
            )
          }
        })}
        {
          item.firstComments ? 
          <View style={styles.commentCommentWrap}>
          {
            item.firstComments.data.map((_firstComment, i) => {
              return (   
                <Text key={_firstComment.key} style={styles.commentCommentContent}>
                  {
                    _firstComment.user.data.name + ": " + 
                    (_firstComment.parentComment ? "回复 " + _firstComment.parentComment.data.user.data.name + ": " : "") + 
                    _firstComment.detail.data.content[0].data.text
                  }
                </Text>  
              )
            })
          }
          </View>
          :
          null
        }
        </View>
        </TouchableWithoutFeedback>
      </View>
    )
  }
}

var styles = StyleSheet.create({
  sectionTopAction: {
    paddingTop: 24,
    justifyContent: "space-between",
    alignItems: "center",
  },
  pagetTitleLeft: {
    alignSelf: "flex-start"
  },
  sectionHeaderWrapper: {
    paddingBottom: 15,
    marginBottom: 5,
  },
  sectionHeader: {
    alignItems: "center",
    justifyContent: "space-between",
  },
  forumDesc: {
    marginLeft: 10,
  }, 
  forumInfo: {
    alignItems: "center",
  },
  forumCover: {

  },
  nickname: {
    marginBottom: 5
  },
  updateTime: {
    fontSize: 12,
  },
  viewCount: {
    fontSize: 12,
  },
  commentCount: {
    fontSize: 12,
  },
  forumName: {
    fontSize: 20,
    marginBottom: 5
  },
  forumStat: {
    marginRight: 10,
  },
  followBtn: {
    width: 50,
    height: 30,
  },
  divider: {
    marginTop: 10,
    marginBottom: 10,
  },

  flatList: {
    marginTop: 4,
  },

  itemWrap: {
    marginBottom: 3,
    paddingTop: 10,
    paddingBottom: 10,
  },
  itemContentWrap: {
    paddingLeft: 34,
  },
  itemSeparator: {
    display: "flex",
    height: 1,
    backgroundColor: "#ddd"
  },
  arrow: {
    position: "absolute",
    right: 0
  },
  countWrap: {
    alignItems: "center",
    marginLeft: 5,
  },
  contentWrap: {
    paddingTop: 10,
    paddingBottom: 10,

  },
  floorWrap: {
    paddingLeft: 80,
  },
  detailAttachmentImage: {
    height: 150
  },
  topicFilter: {
    justifyContent: "space-between",
    alignItems: "center",
    paddingTop: 5,
    paddingBottom: 5,
    borderBottomColor: "#eee",
    borderBottomWidth: 1,
  },
  topicFilterActive: {
    borderBottomWidth: 1,
    borderBottomColor: "#000",
  },
  topicFilterOrder: {
    alignItems: "center",
  },
  mainFloorInfoHeader: {
    justifyContent: "space-between"
  },
  commentCommentWrap: {
    backgroundColor: "#eee",
    padding: 10,
    marginTop:10,
  },
  commentCommentContent: {
    flexWrap: "wrap",
    marginBottom: 10,
  },
  textInputWrap: {
    height: 40,
  },
  textInput: {
    width: "88%",
    padding: 10,
    textAlignVertical: "top",
    backgroundColor: "#eee",
  },
  submitBtn: {
    display: "flex",
    width: "12%",
    justifyContent: "center",
    alignItems: "center",
  },
  loadingMore: {
    paddingVertical: 20,
    borderTopWidth: 1,
    borderColor: "#CED0CE"
  }

})

export default CommentItem;